package com.myJava.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myJava.entity.*;
import com.myJava.service.IVoteDetailService;
import com.myJava.service.IVoteItemService;
import com.myJava.service.IVoteService;
import com.myJava.service.WxUserInfoService;
import com.myJava.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 投票Controller控制器
 * @author csy
 * 
 * 
 */
@RestController
@RequestMapping("/business/vote")
public class VoteController {

    @Autowired
    private IVoteService voteService;

    @Autowired
    private IVoteItemService voteItemService;

    @Autowired
    private IVoteDetailService voteDetailService;

    @Autowired
    private WxUserInfoService wxUserInfoService;

    /**
     * 根据条件分页查询投票信息
     * @param pageBean
     * @return
     */
    @PostMapping("/list")
    @PreAuthorize("hasAuthority('business:vote:list')")
    public R list(@RequestBody PageBean pageBean){
        String query=pageBean.getQuery().trim();
        Page<Vote> pageResult = voteService.page(new Page<>(pageBean.getPageNum(), pageBean.getPageSize()), new QueryWrapper<Vote>().like(StringUtil.isNotEmpty(query), "title", query));
        List<Vote> voteList = pageResult.getRecords();
        for(Vote vote:voteList){
            // 根据openid获取投票人信息
            WxUserInfo wxUserInfo = wxUserInfoService.getOne(new QueryWrapper<WxUserInfo>().eq("openid", vote.getOpenid()));
            // 获取投票选项
            List<VoteItem> voteItemList = voteItemService.list(new QueryWrapper<VoteItem>().eq("vote_id", vote.getId()));
            vote.setVoteItemList(voteItemList);
            vote.setWxUserInfo(wxUserInfo);
        }
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("voteList",voteList);
        resultMap.put("total",pageResult.getTotal());
        return R.ok(resultMap);
    }

    /**
     * 删除指定id的投票信息
     * @param id
     * @return
     */
    @GetMapping("/delete/{id}")
    @Transactional
    @PreAuthorize("hasAuthority('business:vote:delete')")
    public R delete(@PathVariable(value = "id")Integer id){
        voteDetailService.remove(new QueryWrapper<VoteDetail>().eq("vote_id",id)); // 删除用户投票详情
        voteItemService.remove(new QueryWrapper<VoteItem>().eq("vote_id",id)); // 删除投票选项
        voteService.removeById(id); // 删除投票
        return R.ok();
    }

}
